//
//  MateKingAgeFlowLayout.swift

//
//  Created by dongyx on 2023/2/20.
//

import UIKit

class MateKingAgeFlowLayout: UICollectionViewFlowLayout {
    
    override func prepare() {
        super.prepare()
        scrollDirection = .horizontal;
        itemSize = CGSize(width: 60, height: 60)
    }
    
    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
        return true
    }
    
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        var oldRect = rect
        oldRect.size.width = oldRect.size.width + .screenWidth
        oldRect.origin.x = oldRect.origin.x - .screenWidth/2
        guard let array = super.layoutAttributesForElements(in: oldRect) else { return [] }
        return array
    }

    override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
        var rect = CGRect.zero
        rect.origin.y = 0
        rect.origin.x = proposedContentOffset.x
        rect.size = (self.collectionView?.frame.size)!
        guard let array = super.layoutAttributesForElements(in: rect) else { return CGPoint.zero }
        let centerX = proposedContentOffset.x + (self.collectionView?.frame.size.width)! * 0.5
        var minDelta = MAXFLOAT
        for item in array {
            if abs(minDelta) > abs(Float(item.center.x - centerX)) {
                minDelta = Float(item.center.x - centerX);
            }
        }
        var point = proposedContentOffset
        point.x = point.x + CGFloat(minDelta)
        return point
    }
}
